package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.entity.User;
import com.example.springboot.service.ICollectService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Collect;

import org.springframework.web.bind.annotation.RestController;

/**
* CollectAPI接口
*/
@RestController
@RequestMapping("/collect")
public class CollectController {

    @Autowired
    private ICollectService collectService;

    @PostMapping
    public Result save(@RequestBody Collect collect) {
        collectService.save(collect);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Collect collect) {
        collectService.updateById(collect);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        collectService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        collectService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(collectService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(collectService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<Collect>().orderByDesc(Collect::getId);
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser.getRole().equals("USER")){
            queryWrapper.eq(Collect::getUserId,currentUser.getId());
        }
        Page<Collect> page = collectService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    /**
     * 用户-我的收藏
     */
    @GetMapping("/myCollect")
    public Result myCollect() {
        return Result.success(collectService.myCollect());
    }
}
